﻿using System;
using System.Linq;
using WinRTFramework.FrameworkConfiguration;
using WinRTFramework.Interfaces.Contracts.Sharing;
using WinRTFramework.Interfaces.Navigation;
using Windows.ApplicationModel.Activation;

namespace WinRTFramework.FrameworkCore.Managers
{
    internal class SharingTargetManager
    {
        private readonly INavigationService _navigationService;
        private readonly IIoCAdapter _iocAdapter;

        public SharingTargetManager(INavigationService navigationService, IIoCAdapter iocAdapter)
        {
            _navigationService = navigationService;
            _iocAdapter = iocAdapter;
        }

        public ISharingTargetViewModelTypeSelector SharingTargetViewModelTypeSelector { get; set; }

        public void HandleShareActivation(ShareTargetActivatedEventArgs shareTargetActivatedEventArgs)
        {
            Type viewModelType = null;

            if (SharingTargetViewModelTypeSelector != null)
                viewModelType = GetViewModelTypeFromSelector(shareTargetActivatedEventArgs);
            else
                viewModelType = GetViewModelTypeFromIoCContainer();

            _navigationService.Navigate(viewModelType, shareTargetActivatedEventArgs);
        }

        private Type GetViewModelTypeFromIoCContainer()
        {
            Type viewModelType =
                _iocAdapter.GetAllRegisteredTypesThatImplement<ISupportSharingTargetContract>().FirstOrDefault();
            if(viewModelType == null)
                throw new InvalidOperationException("IoC Container contains no ViewModel that implements ISupportSharingTargetContract. Consider providing such a ViewModel if you want your application to support sharing. Otherwise provide a ISharingTargetViewModelTypeSelector to the container's Extensions property.");

            return viewModelType;
        }

        private Type GetViewModelTypeFromSelector(ShareTargetActivatedEventArgs shareTargetActivatedEventArgs)
        {
            Type viewModelType = SharingTargetViewModelTypeSelector.GetViewModelTypeForSharedDataTypes(shareTargetActivatedEventArgs.ShareOperation.Data.AvailableFormats);

            if (viewModelType == null)
                throw new InvalidOperationException("ViewModel Type has to be provided by the ISharingTargetViewModelTypeSelector for any given sharing data type that is specified in the application's capabilities");

            return viewModelType;
        }
    }
}
